package com.brainhealth.utils;

import com.alibaba.fastjson.JSON;
import com.brainhealth.common.enums.PayBusinessType;
import com.brainhealth.common.enums.PayType;
import com.huifu.adapay.Adapay;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.huifu.adapay.model.MerConfig;
import com.huifu.adapay.model.Payment;
import com.huifu.adapay.model.Refund;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class AdapayUtils
{
    protected static final Logger logger = LoggerFactory.getLogger(AdapayUtils.class);

    public static final String ADAPAY_APP_ID = "app_5d5c4b6f-fe25-4b8c-a275-0d5045e66a2b";
    public static final String ADAPAY_PAY_CALLBACK = "https://www.ainaoxingdong.com/brainapi/customer/order/payCallback";
    //public static final String ADAPAY_PAY_CALLBACK_SCORE_RECHARGE = "https://www.ainaoxingdong.com/brainapi/score/v1/score_recharge_order_callback";
    //public static final String ADAPAY_PAY_CALLBACK = "http://42075cf6.r8.cpolar.top/customer/order/payCallback";
    public static final String ADAPAY_PAY_CALLBACK_SCORE_RECHARGE = "http://7255ddb.r1.cpolar.top/score/v1/score_recharge_order_callback";
    public static void initAdapay() throws Exception
    {
        /**
         * 初始化商户配置，服务器启动前，必须通过该方式初始化商户配置完成
         * apiKey为prod模式的API KEY
         * mockApiKey为mock模式的API KEY
         * rsaPrivateKey为商户发起请求时，用于请求参数加签所需要的RSA私钥
         */
        /**
         * 初始化完成，可以开始交易
         */
        String apiKey = "api_live_3a672edc-49e0-4927-9f01-dfd0c7567cac";
        String mockApiKey = "api_test_5db3fea4-9bc3-4471-8101-fc9f9b9c4a98";
        String rsaPrivateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMr+ZEK3GY1dqRiES6ql1PmhDXHIKQJQOCP2y7QfjHVldCN6pSc7lZlw+o+5txsSTYLzz8xpJq4kBA+REOUqVQ2hg5ExeW03BE3zQm1sUpYyhsK5d7bSwmDaodbs5/SUJIsLLUFxs6To+sf+xAFSLk4mUMofc9ouL5/8MASGSmUtAgMBAAECgYEAmc3WOZZyDeKBVMooasvrapjUjvmR2ObfIqDEB15AFlMghCFRMUC8QN6ReoTEcAaWJDqHn+GsJRW03faUTo6ckbVeln+z7DxSsmr61SSxqqsPFFJPSYsSr24vlGq0ILVYxeaz12KEdINBJupZIeT1fLf7HUgsGJ7bC67aZ71p2AECQQDxnJ7FKxloCcWyf6wb+SfRH2y7o43tOk4SdLAU7/jsQmH2vjYb7hhDeqbgB2MvlJHkf55aeiNPB6fuHMtB+4BtAkEA1xUJnGI6UY/XVEiCDGLBa8m/J+uGbN8q0pMs5QpHFUEWO++xg70ZdER6zqQjZ1DZWNT6wUGjrZp9YuHSKIr/wQJALV4tafSH1sNO/g9/L9l/IoN2FV3Gvq7eDhUfIy9UXHiykHRzEJeKstELGLIKa9rH8lIMWAzrKGHVpJ5/hCpHmQJAXv8Juaqg+3k+sBk+Z14O9B6tcWJTgy6maU9b2uXJM5gFy/84NmmFHpdIbpCMmotZFCUtg8IMGxdLHiuDeSi7gQJBAMipGCLtYYUrN9mzkzHnrkEa6FgT5zW0n/o/WDf/9IG5ep+dG45cw3DvNNHgHXOCxflmeXxCW25eSTctkXzq67k=";
        MerConfig merConfig = new MerConfig();
        merConfig.setApiKey(apiKey);
//        merConfig.setApiMockKey(mockApiKey);
        merConfig.setRSAPrivateKey(rsaPrivateKey);
        Adapay.initWithMerConfig(merConfig);
    }


    /**
     * 执行一个支付交易
     *
     * @return 创建的支付对象
     * @throws Exception 异常
     */
    public static Map<String, Object> executePayment(String orderId, PayType payType, BigDecimal payAmount, String openId, PayBusinessType payBusinessType)
    {
        //创建支付对象的参数，全部参数请参考 https://docs.adapay.tech/api/index.html
        Map<String, Object> paymentParams = new HashMap<>(10);
        // 设置超时时间 单位毫秒 类型 int
        // adapay_connection_request_timeout 类型 int, 单位：毫秒 ms
        // 非必须, 默认 10000 指从连接池获取连接的 timeout
//        paymentParams.put("adapay_connection_request_timeout", 1500);
        // adapay_connect_timeout 单位：毫秒 ms
        // 非必须, 默认 30000 指客户端和服务器建立连接的timeout
//        paymentParams.put("adapay_connect_timeout", 1500);
        // adapay_socket_timeout 单位：毫秒 ms
        // 非必须, 默认 30000 指客户端从服务器读取数据的timeout，超出后会抛出SocketTimeOutException
//        paymentParams.put("adapay_socket_timeout", 1500);

        // 设置网络区域
        // 非必须, 默认 shanghai, 如果要使用其他区域请提交工单备注服务器公网出口IP地址申请开通（如：beijing）
//        paymentParams.put("adapay_region", "beijing");
        paymentParams.put("app_id", ADAPAY_APP_ID);
        paymentParams.put("order_no", orderId);
        if (payType == PayType.Alipay)
        {
            paymentParams.put("pay_channel", "alipay_wap");
        }
        if (payType == PayType.Wechat)
        {
            paymentParams.put("pay_channel", "wx_pub");
            Map<String, Object> mExtend = new HashMap<>();
            mExtend.put("open_id", openId);
            paymentParams.put("expend", mExtend);
        }
        DecimalFormat df = new DecimalFormat("0.00");
        paymentParams.put("pay_amt", new BigDecimal(df.format(payAmount)));
        paymentParams.put("goods_title", "脑常青");
        paymentParams.put("goods_desc", "脑常青");
        paymentParams.put("div_members", "");
        if (PayBusinessType.BUY_PRODUCT.equals(payBusinessType)) {
            paymentParams.put("notify_url", ADAPAY_PAY_CALLBACK);
        } else {
            paymentParams.put("notify_url", ADAPAY_PAY_CALLBACK_SCORE_RECHARGE);
        }
        //调用sdk方法，创建支付，得到支付对象
        Map<String, Object> payment = new HashMap<>();
        try
        {
            logger.info("支付交易，请求参数：" + JSON.toJSONString(paymentParams));
            payment = Payment.create(paymentParams);
        } catch (BaseAdaPayException e)
        {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        logger.info("支付交易，返回参数：" + JSON.toJSONString(payment));
        return payment;
    }


    /**
     * 执行一个退款交易
     *
     * @param paymentId 要退款的原支付paymentId
     * @return 创建的退款对象
     * @throws Exception 异常
     */
    public static Map<String, Object> executeRefund(String paymentId, String refundAmount, String orderId)
    {
        Map<String, Object> refundParams = new HashMap<String, Object>(2);
        refundParams.put("refund_amt", refundAmount);
        refundParams.put("app_id", ADAPAY_APP_ID);
        refundParams.put("refund_order_no", orderId);
        Map<String, Object> refund = new HashMap<>();
        try
        {
            logger.info("退款请求参数：" + JSON.toJSONString(refundParams));
            refund = Refund.create(paymentId, refundParams);
        } catch (BaseAdaPayException e)
        {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        logger.info("退款返回参数：" + JSON.toJSONString(refund));
        return refund;
    }

}
